<template>
  <div class="group-buy-add-container">
    <el-card title="新增团购活动">
      <el-form
          ref="groupBuyFormRef"
          :model="groupBuyForm"
          :rules="rules"
          label-width="120px"
          class="group-buy-form"
      >
        <!-- 商户选择（联动商品列表） -->
        <el-form-item label="商户ID" prop="merchantId">
          <el-select
              v-model="groupBuyForm.merchantId"
              placeholder="请选择商户"
              clearable
              @change="handleMerchantChange"
          >
            <el-option
                v-for="merchant in merchants"
                :key="merchant.id"
                :label="`${merchant.id} - ${merchant.name}`"
                :value="merchant.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="团购名" prop="name">
          <el-input v-model="groupBuyForm.name" placeholder="请输入团购名" />
        </el-form-item>

        <el-form-item label="团购描述" prop="description">
          <el-input
              v-model="groupBuyForm.description"
              placeholder="请输入团购描述"
              type="textarea"
          />
        </el-form-item>

        <el-form-item label="团购价格" prop="discount">
          <el-input
              v-model.number="groupBuyForm.discount"
              placeholder="请输入团购价格"
              type="number"
              min="0"
          />
        </el-form-item>

        <el-form-item label="原本价格" prop="price">
          <el-input
              v-model.number="groupBuyForm.price"
              placeholder="请输入原本价格"
              type="number"
              min="0"
          />
        </el-form-item>

        <el-form-item label="团购限购人数" prop="personNum">
          <el-input
              v-model.number="groupBuyForm.personNum"
              placeholder="请输入限购人数"
              type="number"
              step="1"
              min="1"
          />
        </el-form-item>

        <!-- 商户商品列表（带数量选择） -->
        <el-form-item
            v-if="selectedMerchantGoods.length"
            label="选择商品"
            prop="selectedGoods"
        >
          <el-table
              :data="selectedMerchantGoods"
              border
              style="width: 100%"
              @selection-change="handleGoodsSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="商品ID" width="120" align="center"></el-table-column>
            <el-table-column prop="name" label="商品名" align="center"></el-table-column>
            <el-table-column prop="description" label="商品描述" align="center"></el-table-column>
            <el-table-column prop="price" label="商品单价" align="center">
              <template #default="scope">{{ scope.row.price.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="数量" align="center">
              <template #default="scope">
                <el-input-number
                    v-model="scope.row.num"
                    :min="1"
                    :step="1"
                    style="width: 120px"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import server from "../utils/request.js";
import router from "../router/index.js";

// 表单数据
const groupBuyForm = reactive({
  id: '',
  merchantId: '',
  name: '',
  description: '',
  discount: null,
  price: null,
  personNum: null,
  selectedGoods: [] // 存储选中的商品及数量
});

// 商户列表（实际项目从API获取）
const merchants = ref([
  { id: 1, name: '商户A' },
  { id: 2, name: '商户B' },
  { id: 3, name: '商户C' }
]);
// 新增：存储选中的商品（通过表格事件获取）
const checkedGoods = ref([]);

// 表格选择变化时触发，更新选中的商品
const handleGoodsSelectionChange = (selection) => {
  checkedGoods.value = selection; // selection 就是当前选中的商品数组
};
// 选中商户的商品列表
const selectedMerchantGoods = ref([]);

// 表单验证规则
const rules = {
  id: [
    { required: true, message: '请输入团购ID', trigger: 'blur' }
  ],
  merchantId: [
    { required: true, message: '请选择商户', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入团购名', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入团购价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '团购价格不能为负数', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入原本价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '原本价格不能为负数', trigger: 'blur' }
  ],
  personNum: [
    { required: true, message: '请输入限购人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '限购人数至少为1', trigger: 'blur' }
  ]
};

// 表单引用
const groupBuyFormRef = ref(null);

// 页面挂载时获取商户列表（实际项目中调用API）
onMounted(() => {
  // 模拟API请求获取商户列表
  fetchMerchants();
});

const fetchMerchants =async ()=>{
  let {data:data} = await server.get("merchant")
  merchants.value=data.data
}


// 商户选择变化时加载对应商品
const handleMerchantChange =async (merchantId) => {
  if (!merchantId) {
    selectedMerchantGoods.value = [];
    return;
  }
  // 模拟加载商户商品（实际项目从API获取）
  let {data:data} = await server.get(`goods/merchant/${merchantId}`)
  // 这里根据商户ID返回不同的商品列表
  selectedMerchantGoods.value = data.data
};

// 提交表单
const submitForm = () => {
  groupBuyFormRef.value.validate(async (valid) => {
    if (valid) {
      // 直接使用 checkedGoods 作为选中的商品（无需再筛选）
      if (checkedGoods.value.length === 0) {
        ElMessage.warning('请至少选择一个商品');
        return;
      }

      // 构造提交数据
      const submitData = {
        ...groupBuyForm,
        goodsList: checkedGoods.value.map(item => ({
          id: item.id,
          name: item.name,
          num: item.num,
          price: item.price
        }))
      };
      // 模拟提交（实际项目中替换为API调用）
      let {data:data} = await server.post("groupBuy",submitData)
      if (data.code==200){
        ElMessage.success('团购活动添加成功');
        resetForm();
        router.push("groupBuyList")
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  groupBuyFormRef.value.resetFields();
  selectedMerchantGoods.value = [];
};

// 取消操作
const handleCancel = () => {
  // 实际项目中通常用于返回上一页
  ElMessage.info('已取消操作');
  // 可添加路由跳转：router.back()
  router.back()
};
</script>

<style scoped>
.group-buy-add-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.group-buy-form {
  margin-top: 20px;
}

::v-deep .el-form-item__content {
  max-width: 600px;
}
</style>